package com.wlsk.license.common.utils;

import cn.hutool.core.bean.BeanUtil;
import com.zhongjinfeng.util.base.ObjectHelper;
import org.springframework.beans.BeanUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.stream.Collectors;

public class ConvertUtil {

    public static byte[] obj2bytes(Object src) throws IOException {
        if (src == null)
            return null;
        try(ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream output = new ObjectOutputStream(out)) {
            output.writeObject(src);
            return out.toByteArray();
        }
    }

    /**
     * 转换单个对象
     */
    public static <S, T> T copy(S source, Class<T> targetClass) {
        if (source == null) return null;
        T target = BeanUtils.instantiateClass(targetClass);
        ObjectHelper.writeWithFrom(target, source);
        return target;
    }

    /**
     * 转换列表
     */
    public static <S, T> List<T> copyList(List<S> sources, Class<T> targetClass) {
        if (sources == null) return null;
        return sources.stream()
                .map(source -> copy(source, targetClass))
                .collect(Collectors.toList());
    }
}
